package com.example.weather_news.activity;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.example.weather_news.R;
import com.example.weather_news.db.CityInfo;
import com.example.weather_news.db.SaveCityInfo;
import com.example.weather_news.http.HttpRequest;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

public class QueryCityActivity extends AppCompatActivity {

    private static final int LEVEL_PROVINCE = 0;//省

    private static final int LEVEL_CITY = 1;//市

    private static final int LEVEL_COUNTY = 2;//县

    private int currentLevel;//当前选中级别
    private ImageView iv_city_back;
    private TextView tv_cityName;
    private ListView listView_city;

    private List<CityInfo> infos = new ArrayList<CityInfo>();
    private List<String> lists = new ArrayList<String>();

    private Cursor cursor;

    private ArrayAdapter<String> adapter;
    private CityInfo info;
    private CityInfo info1;
    private SaveCityInfo save;

    private String cityName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        int a=DataSupport.findAll(SaveCityInfo.class).size();
//        if (a>0){
//            startActivity(new Intent(QueryCityActivity.this,MainActivity.class));
//            finish();
//            return;
//        }
        setContentView(R.layout.activity_query_city);
        initView();

        if (DataSupport.findAll(CityInfo.class).size() > 0) {
            Log.e("lists", DataSupport.findAll(CityInfo.class).size() + "");
        } else {
            queryCityName();
        }

        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lists);
        listView_city.setAdapter(adapter);
        //查询省
        queryProvince();

        listView_city.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                info = infos.get(position);
                save = new SaveCityInfo();
                if (currentLevel == LEVEL_PROVINCE) {
                    if (TextUtils.equals("澳门", info.getCity())) {
                        cityName = "澳门";
                        cursor = DataSupport.findBySQL("SELECT * FROM savecityinfo WHERE " +
                                "cityName=?", cityName);
                        if (cursor.getCount() == 0) {
                            Log.e("cityName1", cityName);
                            save.setCityName(cityName);
                            save.save();
                            goToMain();
                        } else {
                            goToMain();
                        }
                    } else {
                        info1 = infos.get(position);
                        queryCity();
                    }
                } else if (currentLevel == LEVEL_CITY) {
                    //判断是否是直辖市
                    if (TextUtils.equals("1", info.getParentid()) ||
                            TextUtils.equals("8", info.getParentid()) ||
                            TextUtils.equals("24", info.getParentid()) ||
                            TextUtils.equals("26", info.getParentid()) ||
                            TextUtils.equals("31", info.getParentid()) ||
                            TextUtils.equals("32", info.getParentid()) ||
                            TextUtils.equals("34", info.getParentid())) {

                        cityName = info.getCity();
                        cursor = DataSupport.findBySQL("SELECT * FROM savecityinfo WHERE " +
                                "cityName=?", cityName);
                        if (cursor.getCount() == 0) {
                            Log.e("cityName2", cityName);
                            save.setCityName(cityName);
                            save.save();
                            goToMain();
                        } else {
                            Log.e("2", 2 + "");
                            goToMain();
                        }
                    } else {
                        queryCounty();
                    }
                } else if (currentLevel == LEVEL_COUNTY) {
                    cityName = info.getCity();
                    cursor = DataSupport.findBySQL("SELECT * FROM savecityinfo WHERE cityName=?",
                            cityName);
                    if (cursor.getCount() == 0) {
                        Log.e("cityName3", cityName);
                        save.setCityName(cityName);
                        save.save();
                        goToMain();
                    } else {
                        Log.e("3", 3 + "");
                        goToMain();
                    }
                }

            }
        });

        iv_city_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setBackCity();
            }
        });
    }

    //选择城市后跳转到MainActivity

    private void goToMain(){
        setResult(1, new Intent());//向上一个Activity发送信息，finish()掉Activity
        finish();
    }


    /**
     * 返回图标设置
     */
    private void setBackCity() {
        if (currentLevel == LEVEL_COUNTY) {
            queryCity1();
        } else if (currentLevel == LEVEL_CITY) {
            queryProvince();
        } else if (currentLevel == LEVEL_PROVINCE) {
            iv_city_back.setVisibility(View.GONE);
        }
    }

    /**
     * 查询县级城市
     */
    private void queryCounty() {
        currentLevel = LEVEL_COUNTY;
        lists.clear();
        infos.clear();
        tv_cityName.setText(info.getCity());
        iv_city_back.setVisibility(View.VISIBLE);
        infos = DataSupport.where("parentid=?", info.getCityid()).find(CityInfo.class);
        String city;
        for (int i = 0; i < infos.size(); i++) {
            city = infos.get(i).getCity();
            lists.add(city);
            if (lists.size() == infos.size()) {
                adapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 查询市级城市
     */
    private void queryCity() {
        currentLevel = LEVEL_CITY;
        lists.clear();
        infos.clear();
        tv_cityName.setText(info.getCity());
        iv_city_back.setVisibility(View.VISIBLE);
        Log.e("cityID", info.getCityid());
        infos = DataSupport.where("parentid=?", info.getCityid()).find(CityInfo.class);
        String city;
        for (int i = 0; i < infos.size(); i++) {
            city = infos.get(i).getCity();
            lists.add(city);
            if (lists.size() == infos.size()) {
                adapter.notifyDataSetChanged();
            }
        }
    }

    private void queryCity1() {
        currentLevel = LEVEL_CITY;
        lists.clear();
        infos.clear();
        tv_cityName.setText(info1.getCity());
        iv_city_back.setVisibility(View.VISIBLE);
        Log.e("cityID", info.getCityid());
        infos = DataSupport.where("parentid=?", info1.getCityid()).find(CityInfo.class);
        String city;
        for (int i = 0; i < infos.size(); i++) {
            city = infos.get(i).getCity();
            lists.add(city);
            if (lists.size() == infos.size()) {
                adapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 查询省级
     */
    private void queryProvince() {
        currentLevel = LEVEL_PROVINCE;
        lists.clear();
        infos.clear();
        tv_cityName.setText("中国");
        iv_city_back.setVisibility(View.GONE);
        infos = DataSupport.where("parentid=0").find(CityInfo.class);
        Log.e("infos", infos.size() + "");
        String city;
        for (int i = 0; i < infos.size(); i++) {
            city = infos.get(i).getCity();
            lists.add(city);
            if (lists.size() == infos.size()) {
                adapter.notifyDataSetChanged();
            }
        }
    }


    private void queryCityName() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpRequest.requestCity(new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            if (jsonObject.getInt("status") != 0) {
                                Toast.makeText(QueryCityActivity.this, jsonObject.getString
                                        ("msg"), Toast
                                        .LENGTH_SHORT).show();
                                return;
                            }
                            JSONArray array = new JSONArray(jsonObject.getString("result"));
                            Log.e("array1", array.length() + "");
                            Gson gson = new Gson();
                            CityInfo info;
                            for (int i = 0; i < array.length(); i++) {
                                info = gson.fromJson(array.getJSONObject(i).toString(), CityInfo
                                        .class);
                                info.save();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, null);
            }
        }).start();
    }



    private void initView() {
        iv_city_back = (ImageView) findViewById(R.id.iv_city_back);
        tv_cityName = (TextView) findViewById(R.id.tv_cityName);
        listView_city = (ListView) findViewById(R.id.listView_city);
    }
}
